<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-8-15
 * Time: 下午2:25
 */

namespace appapi\behaviors;


use common\components\tools\ArrayHelper;
use common\members\wodrow\tools\Model;
use common\models\db\Equipment;
use common\models\db\EquipmentAppVersion;
use common\models\db\EquipmentAppVersionUpdateLog;
use common\models\db\EquipmentOperateLog;
use common\rewrite\deepziyu\yii_fast_api\ApiException;
use yii\base\ActionFilter;
use yii\db\Exception;

/**
 * 检测是否用设备app操作并保存操作记录
 * Class EquipmentCheck
 * @package api\behaviors
 */
class EquipmentCheck extends ActionFilter
{
    /**
     * @param \yii\base\Action $action
     * @return bool
     * @throws ApiException
     * @throws Exception
     * @throws \yii\base\Exception
     */
    public function beforeAction($action)
    {
        $params = ArrayHelper::merge(\Yii::$app->request->get(), \Yii::$app->request->post());
        if (!isset($params['uuid'])) {
            throw new ApiException(201808151432, '请求项必须有设备唯一标识');
        }
        if (strlen($params['uuid']) < 1) {
            throw new ApiException(201808151433, '设备唯一标识必须是一个非空字符串');
        }
        if (!isset($params['app_version_id'])) {
            throw new ApiException(201808151434, '请求项必须有设备安装的app版本ID');
        }
        $app_version = EquipmentAppVersion::findOne(['app_version_id' => $params['app_version_id']]);
        if (!$app_version) {
            throw new ApiException(201808151435, '数据库没有找到app版本信息');
        }
        $trans = \Yii::$app->db->beginTransaction();
        try {
            $equipment = Equipment::generateEquipment($params['uuid'], $params['app_version_id']);
            if ($equipment->app_version_id != $app_version->id) {
                $log = new EquipmentAppVersionUpdateLog();
                $log->equipment_id = $equipment->id;
                $log->old_version_id = $equipment->app_version_id;
                $log->new_version_id = $app_version->id;
                $log->happen_from = EquipmentAppVersionUpdateLog::HAPPEN_FROM_API;
                $log->happen_at = Yii_BT_TIME;
                if (!$log->save()) {
                    throw new Exception("设备app安装版本更新添加记录失败:" . Model::getModelError($log));
                }
            }
            $equipment->app_version_id = $app_version->id;
            if (!$equipment->save()) {
                throw new Exception("设备app安装版本更新失败:" . Model::getModelError($equipment));
            }
            $params = ArrayHelper::merge(\Yii::$app->request->get(), \Yii::$app->request->post());
            $equipmentOperateLog = new EquipmentOperateLog();
            $equipmentOperateLog->equipment_id = $equipment->id;
            $equipmentOperateLog->action_route = $action->controller->route;
            $equipmentOperateLog->operate_type = EquipmentOperateLog::OPERATE_NOT_DEFINED;
            if (isset($params['password']))unset($params['password']);
            $equipmentOperateLog->req_data = json_encode($params);
            $equipmentOperateLog->created_at = Yii_BT_TIME;
            $trans->commit();
        } catch (Exception $e) {
            $trans->rollBack();
            throw new ApiException(201808151624, $e->getMessage());
        }
        \Yii::$app->equipmentInfo->setEquipment($equipment);
        \Yii::$app->equipmentInfo->setEquipmentOperateLog($equipmentOperateLog);
        \Yii::$app->equipmentInfo->setEquipmentAppVersion($app_version);
        return parent::beforeAction($action);
    }

    /**
     * @param \yii\base\Action $action
     * @param mixed $result
     * @return mixed
     * @throws ApiException
     * @throws \yii\base\Exception
     */
    public function afterAction($action, $result)
    {
        $equipmentOperateLog = \Yii::$app->equipmentInfo->equipmentOperateLog;
        $equipmentOperateLog->resp_data = json_encode($result);
        if (!$equipmentOperateLog->save()){
            throw new ApiException(201808142021, '设备操作记录保存失败:'.Model::getModelError($equipmentOperateLog));
        }
        return parent::afterAction($action, $result);
    }
}